/** 定义控制器层 */
app.controller('goodsController', function($scope, $controller, baseService){


    /** 指定继承baseController */
    $controller('baseController',{$scope:$scope});



   /**   1. 添加或修改 */
    $scope.saveOrUpdate = function(){
        $scope.goods.goodsDesc.introduction=editor.html();

               baseService.sendPost("/goods/save", $scope.goods)
                   .then(function(response){
                       if (response.data){
                           /** 重新加载数据 */
                          editor.html("")
                           $scope.goods={};
                           $scope.reload();
                       }else{
                           alert("操作失败！");
                       }
                   });
    };



// 2.上传文件
    $scope.upload=function () {
        baseService.uploadFile().then(function (responce) {
            if (responce.data.status==200){
                $scope.pic.url=responce.data.url;
            }


        })

    }


    // 添加图片到数组
    $scope.goods = {goodsDesc : {itemImages : [], specificationItems : []}}
     $scope.addPic=function (pic) {
         $scope.goods.goodsDesc.itemImages.push(pic)

    }

    // 从数组中删除图片
    $scope.deleteImg=function(index){
        $scope.goods.goodsDesc.itemImages.splice(index,1);
    }


// 3.商品的分类三级联动
   //      一级联动
     $scope.findProductByParentId=function (id,name) {
        baseService.sendGet("/itemcat/findById?parentId="+id).then(function (response) {
            $scope[name] = response.data;
        })
     }

    // 二级联动
    $scope.$watch("goods.category1Id",function (newVal,oldVal) {
        if(newVal) {
            // alert(newVal);
            $scope.findProductByParentId(newVal, "product_2");
        }else {
            $scope.product_2=[];
        }

    })

    // 三级联动
    $scope.$watch("goods.category2Id",function (newVal,oldVal) {
        if(newVal) {
            // alert(newVal);
            $scope.findProductByParentId(newVal, "product_3");
        }else {
            $scope.product_3=[];
        }
 })
    // 读取模板id
    $scope.$watch("goods.category3Id",function (newVal, oldVal) {
        if(newVal) {
            // alert(newVal);
            // $scope.findProductByParentId(newVal, "product_3");
            // $scope.product_3
            for(var i=0;i<$scope.product_3.length ;i++){
               if( $scope.product_3[i].id==newVal){
                   $scope.goods.typeTemplateId = $scope.product_3[i].typeId;
                   break;
               }
            }
        }else {
            $scope.goods.typeTemplateId=""
        }
    })
     // 获取当前模板的品牌,扩张属相
    $scope.brandId=[];
    $scope.$watch("goods.typeTemplateId",function (newVal, oldVal) {
        if(newVal){
            // 扩展属性
            baseService.sendGet("/typeTemplateControler/findById?id="+newVal).then(function (response) {
                $scope.brandId=JSON.parse(response.data.brandIds);
                $scope.goods.goodsDesc.customAttributeItems=JSON.parse(response.data.customAttributeItems);
                // $scope.customAttributeItems=JSON.parse(response.data.customAttributeItems);
            })
            // 规格
            baseService.sendGet("/typeTemplateControler/findSpecOptions?id="+newVal).then(function (response) {
                 $scope.specList= response.data;
            })

        }
    })

    // 4.保存规格选项
    // <!--[{"attributeValue":["联通4G","电信4G","移动4G"],"attributeName":"网络"},{"attributeValue":["32G","128G"],"attributeName":"机身内存"}]									<div ng-repeat=" sp in specList">-->
    $scope.addOptions=function (event,attributeName,attributeValue) {
        var searchJsonByKey = $scope.searchJsonByKey($scope.goods.goodsDesc.specificationItems,"attributeName",attributeName);
        // 判断是否已存在attributeName，
        if(searchJsonByKey){
        if(event.target.checked){
                searchJsonByKey.attributeValue.push(attributeValue);
        }else {
            // 删除
            var index = searchJsonByKey.attributeValue.indexOf(attributeValue);
            searchJsonByKey.attributeValue.splice(index,1);

        }
     }else {
            $scope.goods.goodsDesc.specificationItems.push({"attributeName":attributeName,"attributeValue":[attributeValue]})
        }

    }

    // 判断$scope.goods.goodsDesc.specificationItems数组中是否存在相同的attributeName
    $scope.searchJsonByKey=function (jsonArr, key, value) {
     // 遍历数据
        //jsonArr:
        // [{"attributeValue":["联通4G","电信4G","移动4G"],"attributeName":"网络"},{"attributeValue":["32G","128G"],"attributeName":"机身内存"}]
        for(var i=0;i<jsonArr.length;i++){
            var arr = jsonArr[i];
            if(arr[key]==value){
                return arr;
            }
        }
    }

    // 根据复选框是否选中，来创建items
    $scope.createItems=function () {
        /** 定义SKU数组，并初始化 */
        $scope.goods.items = [{spec:{}, price:0, num:9999, status:'0', isDefault:'0' }];

        var specificationItems = $scope.goods.goodsDesc.specificationItems;
        //specificationItems:[{"attributeValue":["联通4G","电信4G","移动4G"],"attributeName":"网络"},{"attributeValue":["32G","128G"],"attributeName":"机身内存"}]
         // 遍历
        // spec:{"网络":"联通4G","机身内存":"64G"}
        for(var i=0;i<specificationItems.length;i++){
            $scope.goods.items = swapItems($scope.goods.items,
                    specificationItems[i].attributeName,
                    specificationItems[i].attributeValue);
        }
    }

    // 扩充SUK数组
  var swapItems=function (items, attributeName, attributeValue) {
         // 创建新的suk数组
         var newItems= new Array();
         // 遍历旧的sku数组
        for(var i=0;i<items.length;i++){
            // 获取一个sku商品
          var item = items[i];
            for(var j=0;j<attributeValue.length;j++){
                // 将旧的sku商品，放到新的sku商品中
                   var newItem = JSON.parse(JSON.stringify(item));
                   newItem.spec[attributeName]=attributeValue[j];
                   // 将新的sku商品放到新的sku数组中
                  newItems.push(newItem);
            }
        }
        return newItems;
    }



    /** 查询条件对象 */
    $scope.searchGoods = {};
    /** 分页查询(查询条件) */
    $scope.search = function(page, rows){
        baseService.findByPage("/goods/findByPage", page,
            rows, $scope.searchGoods)
            .then(function(response){
                /** 获取分页查询结果 */
                $scope.dataList = response.data.list;
                console.log("data==="+response.data.list)

                /** 更新分页总记录数 */
                $scope.paginationConf.totalItems = response.data.totalItems;
            });
    };




    //
    //
    //
    // /** 显示修改 */
    // $scope.show = function(entity){
    //    /** 把json对象转化成一个新的json对象 */
    //    $scope.entity = JSON.parse(JSON.stringify(entity));
    // };
    //
    // /** 批量删除 */
    // $scope.delete = function(){
    //     if ($scope.ids.length > 0){
    //         baseService.deleteById("/goods/delete", $scope.ids)
    //             .then(function(response){
    //                 if (response.data){
    //                     /** 重新加载数据 */
    //                     $scope.reload();
    //                 }else{
    //                     alert("删除失败！");
    //                 }
    //             });
    //     }else{
    //         alert("请选择要删除的记录！");
    //     }
    // };
});